package com.sunday.aomicaichang.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.sunday.common.adapter.CommenAdapter;
import com.sunday.common.adapter.ViewHolder;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.MD5Utils;
import com.sunday.common.utils.SharePerferenceUtils;
import com.sunday.common.utils.StringUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.NoScrollListview;
import com.sunday.common.widgets.taosty.Toasty;
import com.sunday.aomicaichang.R;
import com.sunday.aomicaichang.base.BaseApp;
import com.sunday.aomicaichang.constValues.ConstValue;
import com.sunday.aomicaichang.ui.my.AddressListActivity;
import com.sunday.member.entity.addr.Address;
import com.sunday.member.entity.order.OrderConfirm;
import com.sunday.member.entity.order.OrderItem;
import com.sunday.member.entity.order.OrderProduct;
import com.sunday.member.http.MemberClient;
import com.sunday.member.utils.SignUtil;

import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class MallOrderConfirmActivity extends BaseActivity {

    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title_bar)
    RelativeLayout titleBar;
    @Bind(R.id.img)
    ImageView img;
    @Bind(R.id.view)
    View view;
    @Bind(R.id.ly)
    RelativeLayout ly;
    @Bind(R.id.tv)
    TextView tv;
    @Bind(R.id.user_name)
    TextView userName;
    @Bind(R.id.user_mobile)
    TextView userMobile;
    @Bind(R.id.linearlayout)
    LinearLayout linearlayout;
    @Bind(R.id.user_addr)
    TextView userAddr;
    @Bind(R.id.select_img)
    ImageView selectImg;
    @Bind(R.id.address_layout)
    RelativeLayout addressLayout;
    @Bind(R.id.list_view)
    NoScrollListview listView;
    @Bind(R.id.tv_post)
    TextView tvPost;
    @Bind(R.id.tv_send_price)
    TextView tvSendPrice;
    @Bind(R.id.btn_next)
    TextView btnNext;
    @Bind(R.id.tv_price)
    TextView tvPrice;
    private OrderConfirm orderConfirm;
    private CommenAdapter<OrderProduct> adapter;
    private int isUsedBalance = 0;
    private boolean selectBalance = false;
    private int couponId;
    private int sendType = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_confrim_exchange_order);
        ButterKnife.bind(this);
        orderConfirm = (OrderConfirm) getIntent().getSerializableExtra("orderConfirm");
        initView();
        getDefaultAddr();
    }

    private void initView() {
        if (orderConfirm == null) {
            return;
        }
        if (TextUtils.isEmpty(orderConfirm.getSendAddress())) {
            userName.setText("暂无收货地址");
            userAddr.setText("请选择收货地址");
        } else {
            userAddr.setText(orderConfirm.getSendAddress());
        }
        if(orderConfirm.getTotalAmount()!=null)
        tvPrice.setText(orderConfirm.getTotalAmount()+"");
        if(orderConfirm.getSendAmount()!=null)
        tvSendPrice.setText(orderConfirm.getSendAmount() + "积分");
        if (orderConfirm.getProducts() != null && !orderConfirm.getProducts().isEmpty()) {
            adapter = new CommenAdapter<OrderProduct>(mContext, orderConfirm.getProducts(), R.layout.list_order_confirm_product) {
                @Override
                public void convert(ViewHolder helper, OrderProduct item, int position) {
                    bind(helper, item);
                }
            };
            listView.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        }
        if (orderConfirm.getShopName() != null)
            tv.setText(orderConfirm.getShopName());
    }

    private void bind(ViewHolder helper, OrderProduct item) {
        ImageView imageView = helper.getView(R.id.product_img);
        if (!TextUtils.isEmpty(item.getImage())) {
            Picasso.with(mContext)
                    .load(item.getImage())
                    .error(R.mipmap.ic_product)
                    .resize(150, 150)
                    .into(imageView);
        }
        ((TextView) helper.getView(R.id.product_title)).setText(item.getName());
        ((TextView) helper.getView(R.id.product_price)).setText(String.format("￥%s", item.getPrice().setScale(2, RoundingMode.HALF_UP)));
        ((TextView) helper.getView(R.id.product_num)).setText(String.format("X%d", item.getNum()));
        ((TextView) helper.getView(R.id.product_spec)).setText("规格:" + item.getStandard());
    }

    private Address address;

    private void getDefaultAddr() {
        String nonce = MD5Utils.random();
        long memberId = BaseApp.getInstance().getMember().getId();
        String[] str1 = new String[]{"nonce"};
        String[] str2 = new String[]{ nonce};
        showLoadingDialog(0);
        Call<ResultDO<List<Address>>> call = MemberClient.getApiAdapter().getAddrList(nonce, SignUtil.getSign(str1, str2));
        call.enqueue(new Callback<ResultDO<List<Address>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<Address>>> call, Response<ResultDO<List<Address>>> response) {
                if (isFinish) {
                    return;
                }
                dissMissDialog();
                ResultDO<List<Address>> resultDO = response.body();
                if (resultDO == null) {
                    return;
                }
                if (resultDO.getCode() == 0) {
                    if (resultDO.getResult() == null) {
                        return;
                    }
                    if (resultDO.getResult() != null && !resultDO.getResult().isEmpty()) {
                        address = resultDO.getResult().get(0);
                        setAddr(address);
                    }
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<Address>>> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }

    private final static int REQUEST_ADDR = 0x1111;
    private final static int REQUEST_COUPON = 0x1112;

    @OnClick({R.id.btn_next, R.id.address_layout, R.id.tv_post})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_next:
                if (address == null) {
                    Toasty.error(mContext, "请选择收货地址").show();
                    return;
                }
                creatOrder();
                break;
            case R.id.address_layout:
                intent = new Intent(mContext, AddressListActivity.class);
                intent.putExtra("isSelectMode", true);
                startActivityForResult(intent, REQUEST_ADDR);
                break;

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_ADDR:
                address = (Address) data.getSerializableExtra("address");
                setAddr(address);
                break;
        }
    }

    private void setAddr(Address address) {
        if (address == null) {
            userName.setText("暂无收货地址");
            userMobile.setText("");
            userAddr.setText("请添加收货地址");
        } else {
            userName.setText("姓名:" + address.getReceiveName());
            userMobile.setText(address.getReceiveMobile());
            userAddr.setText(String.format("%1$s%2$s%3$s%4$s", address.getProvinceName(), address.getCityName(),
                    address.getDistrictName(), address.getReceiveAddress()));
        }
    }


    private List<String> cartIds = new ArrayList<>();

    private void creatOrder() {
        cartIds.clear();
        if (orderConfirm.getProducts() != null && !orderConfirm.getProducts().isEmpty()) {
            for (OrderProduct item : orderConfirm.getProducts()) {
                cartIds.add(String.valueOf(item.getCartId()));
            }
        }
        int villageId = SharePerferenceUtils.getIns(mContext).getInt(ConstValue.AREA, 0);
        String nonce = MD5Utils.random();
        String addressId = String.valueOf(address.getId());
        String cartIdStr = StringUtils.listToString(cartIds);
        String[] str1 = new String[]{"sendType", "villageId", "cartIds", "addressId", "nonce"};
        String[] str2 = new String[]{String.valueOf(sendType), String.valueOf(villageId), cartIdStr, addressId, nonce};
        showLoadingDialog(0);
        Call<ResultDO<OrderItem>> call = MemberClient.getApiAdapter().createOrder(cartIdStr, sendType, null, null, address.getId(), villageId,
                null, null, nonce, SignUtil.getSign(str1, str2));
        call.enqueue(new Callback<ResultDO<OrderItem>>() {
            @Override
            public void onResponse(Call<ResultDO<OrderItem>> call, Response<ResultDO<OrderItem>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                dissMissDialog();
                if (response.body().getCode() == 0) {
                    //暂时先不支付 直接跳转采购订单页面
                    //intent=new Intent(mContext,BuyOrderListActivity.class);
                    // startActivity(intent);
                    intent = new Intent(mContext, MallRechangeSuccessActivity.class);
                    intent.putExtra("totalMoney", String.format("￥%s", orderConfirm.getPayAmount().setScale(2, RoundingMode.HALF_UP)));
                    intent.putExtra("address", address);
                    startActivity(intent);
                    finish();
                } else {
                    Toasty.error(mContext, response.body().getMessage()).show();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<OrderItem>> call, Throwable t) {
                dissMissDialog();
                Toasty.error(mContext, "网络连接错误").show();
            }
        });
    }
}
